/*
 *
 *  Copyright (C) 2012-2024
 *  All rights reserved, Designed By 杭州连线客信息技术有限公司
 *  注意：
 *  本软件为杭州连线客信息技术有限公司开发研制，未经购买不得使用
 *  购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 *  一经发现盗用、分享等行为，将追究法律责任，后果自负
 *
 */

package com.lxk.mall.pms.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lxk.mall.pms.domain.PmsProductSku;
import com.lxk.mall.pms.domain.PmsProductSpu;
import com.lxk.mall.pms.domain.bo.spu.PmsProductSkuBo;
import com.lxk.mall.pms.domain.vo.spu.PmsProductSkuVo;
import com.lxk.mall.pms.domain.vo.spu.PmsProductSpuVo;
import com.lxk.mall.pms.enums.ProductSpuStatusEnum;
import com.lxk.mall.pms.mapper.PmsProductSkuMapper;
import com.lxk.mall.pms.mapper.PmsProductSpuMapper;
import com.lxk.mall.pms.service.IPmsProductSkuService;
import com.lxk.mall.pms.service.IPmsProductSpuService;
import com.lxk.service.core.Result;
import com.lxk.service.pms.api.PmsServiceApi;
import com.lxk.service.pms.request.CheckSkuStockParam;
import com.lxk.service.pms.request.ProductSkuUpdateStockParam;
import com.lxk.service.pms.request.QueryPmsParam;
import com.lxk.service.pms.request.QueryPmsSpuParam;
import com.lxk.service.pms.response.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.CollectionUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.ValidationUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.lxk.mall.pms.enums.PmsErrorCodeConstants.SKU_PARAM_NOT_EMPTY;

/**
 * 用户内部API
 *
 * @author huahua
 * 2024/8/20
 */
@Slf4j
@Service
@AllArgsConstructor
@DS("master")
public class PmsProductServiceApiImpl implements PmsServiceApi {
    private final IPmsProductSkuService skuService;
    private final IPmsProductSpuService spuService;
    private final PmsProductSkuMapper baseMapper;
    private final PmsProductSpuMapper spuMapper;

    @Override
    public Result<PmsProductSkuDto> queryBySkuId(Long skuId) {
        PmsProductSkuVo skuVo = skuService.queryById(skuId);
        PmsProductSkuDto dto = MapstructUtils.convert(skuVo, PmsProductSkuDto.class);
        return Result.ok(dto);
    }

    /**
     * 查询商品sku
     *
     * @return
     */
    @Override
    public Result<PmsProductSkuDto> querySkuByParam(QueryPmsParam param) {
        if (param.getId() == null) {
            throw new ServiceException("id不能为空");
        }
        PmsProductSkuVo skuVo = baseMapper.selectVoOne(new LambdaQueryWrapper<PmsProductSku>()
            .eq(PmsProductSku::getId, param.getId())
            .eq(param.getMerId() != null, PmsProductSku::getMerId, param.getMerId())
            .eq(param.getSpuId() != null, PmsProductSku::getSpuId, param.getSpuId()));
        PmsProductSkuDto dto = MapstructUtils.convert(skuVo, PmsProductSkuDto.class);
        return Result.ok(dto);
    }

    /**
     * 查询sku列表
     *
     * @param param
     * @return
     */
    @Override
    public Result<List<PmsProductSkuDto>> querySkuListByParam(QueryPmsParam param) {
        List<PmsProductSkuVo> skuVoList = baseMapper.selectVoList(new LambdaQueryWrapper<PmsProductSku>()
            .eq(param.getId() != null, PmsProductSku::getId, param.getId())
            .eq(param.getMerId() != null, PmsProductSku::getMerId, param.getMerId())
            .eq(param.getSpuId() != null, PmsProductSku::getSpuId, param.getSpuId()));
        List<PmsProductSkuDto> skuVoDtoList = MapstructUtils.convert(skuVoList, PmsProductSkuDto.class);
        return Result.ok(skuVoDtoList);
    }

    /**
     * 查询商品spu
     *
     * @return
     */
    @Override
    public Result<PmsProductSpuDto> querySpuByParam(QueryPmsSpuParam param) {
        if (param.getId() == null) {
            throw new ServiceException("id不能为空");
        }
        PmsProductSpuVo skuVo = spuMapper.selectVoOne(new LambdaQueryWrapper<PmsProductSpu>()
            .eq(PmsProductSpu::getId, param.getId())
            .eq(param.getMerId() != null, PmsProductSpu::getMerId, param.getMerId())
            .eq(param.getStatus() != null, PmsProductSpu::getStatus, param.getStatus()));
        PmsProductSpuDto dto = MapstructUtils.convert(skuVo, PmsProductSpuDto.class);
        if (dto != null && dto.getId() != null) {
            PmsProductSkuBo query = new PmsProductSkuBo();
            query.setSpuId(dto.getId());
            List<PmsProductSkuVo> skuVoList = skuService.queryList(query);
            List<PmsProductSkuDto> skuDtoList = MapstructUtils.convert(skuVoList, PmsProductSkuDto.class);
            dto.setSkuDtoList(skuDtoList);
        }
        return Result.ok(dto);
    }

    /**
     * 查询spu列表
     *
     * @param param
     * @return
     */
    @Override
    public Result<List<PmsProductSpuDto>> querySpuListByParam(QueryPmsSpuParam param) {
        List<PmsProductSpuVo> spuVoList = spuMapper.selectVoList(new LambdaQueryWrapper<PmsProductSpu>()
            .eq(PmsProductSpu::getId, param.getId())
            .eq(param.getMerId() != null, PmsProductSpu::getMerId, param.getMerId())
            .eq(param.getStatus() != null, PmsProductSpu::getStatus, param.getStatus()));
        List<PmsProductSpuDto> spuDtoList = MapstructUtils.convert(spuVoList, PmsProductSpuDto.class);
        if (CollUtil.isNotEmpty(spuDtoList)) {
            List<Long> spuIdList = spuDtoList.stream().map(PmsProductSpuDto::getId).toList();
            List<PmsProductSkuVo> skuVoList = skuService.getSkuListBySpuId(spuIdList);
            List<PmsProductSkuDto> skuDtoList = MapstructUtils.convert(skuVoList, PmsProductSkuDto.class);
            Map<Long, List<PmsProductSkuDto>> map = CollectionUtils.convertMultiMap(skuDtoList, PmsProductSkuDto::getSpuId);
            spuDtoList.forEach(spuDto -> spuDto.setSkuDtoList(map.get(spuDto.getId())));
        }
        return Result.ok(spuDtoList);
    }

    /**
     * 查询ID集合
     *
     * @return
     */
    @Override
    public Result<List<PmsProductSkuDto>> queryBySkuIdList(List<Long> skuIdList) {
        List<PmsProductSkuVo> skuVoList = skuService.queryByIdList(skuIdList);
        List<PmsProductSkuDto> skuVoDtoList = MapstructUtils.convert(skuVoList, PmsProductSkuDto.class);
        return Result.ok(skuVoDtoList);
    }

    /**
     * 更具spuid查询商品spu
     *
     * @param spuId
     * @return
     */
    @Override
    public Result<PmsProductSpuDto> queryBySpuId(Long spuId) {
        PmsProductSpu skuVo = spuService.queryById(spuId);
        PmsProductSpuDto dto = BeanUtil.toBean(skuVo, PmsProductSpuDto.class);
        if (dto != null && dto.getId() != null) {
            PmsProductSkuBo query = new PmsProductSkuBo();
            query.setSpuId(dto.getId());
            List<PmsProductSkuVo> skuVoList = skuService.queryList(query);
            List<PmsProductSkuDto> skuDtoList = MapstructUtils.convert(skuVoList, PmsProductSkuDto.class);
            dto.setSkuDtoList(skuDtoList);
        }
        return Result.ok(dto);
    }

    /**
     * 更具spuid列表查询商品spu
     *
     * @param spuIdList
     * @param needSku
     * @return
     */
    @Override
    public Result<List<PmsProductSpuDto>> queryBySpuIdList(List<Long> spuIdList, Boolean needSku) {
        List<PmsProductSpuVo> spuVoList = spuService.queryByIdList(spuIdList);
        List<PmsProductSpuDto> spuDtoList = MapstructUtils.convert(spuVoList, PmsProductSpuDto.class);
        if (CollUtil.isNotEmpty(spuDtoList) && needSku) {
            List<PmsProductSkuVo> skuVoList = skuService.getSkuListBySpuId(spuIdList);
            List<PmsProductSkuDto> skuDtoList = MapstructUtils.convert(skuVoList, PmsProductSkuDto.class);
            Map<Long, List<PmsProductSkuDto>> map = CollectionUtils.convertMultiMap(skuDtoList, PmsProductSkuDto::getSpuId);
            spuDtoList.forEach(spuDto -> spuDto.setSkuDtoList(map.get(spuDto.getId())));
        }
        return Result.ok(spuDtoList);
    }

    /**
     * 根据SKUID查询库存是否足够
     *
     * @param checkSkuStockParam
     * @return
     */
    @Override
    public Result<SkuCheckStockItemResult> checkStockBySkuId(CheckSkuStockParam checkSkuStockParam) {
        ValidationUtils.validate(checkSkuStockParam);
        SkuCheckStockItemResult result = new SkuCheckStockItemResult();
        result.setSkuId(checkSkuStockParam.getSkuId());
        result.setMerId(checkSkuStockParam.getMerId());
        result.setNum(checkSkuStockParam.getNum());
        result.setResult(Boolean.TRUE);
        PmsProductSkuVo productSkuVo = skuService.queryByIdAndMerId(checkSkuStockParam.getSkuId(), checkSkuStockParam.getMerId());
        if (productSkuVo != null) {
            //校验商品状态
            PmsProductSpu productSpu = spuService.queryById(productSkuVo.getSpuId());
            if (productSpu == null) {
                result.setResult(Boolean.FALSE);
                result.setMessage("商品不存在");
            } else {
                if (!Objects.equals(productSpu.getStatus(), ProductSpuStatusEnum.ENABLE.getStatus())) {
                    result.setResult(Boolean.FALSE);
                    result.setMessage("商品已下架");
                } else {
                    result.setStock(productSkuVo.getStock());
                    if (productSkuVo.getStock() < checkSkuStockParam.getNum()) {
                        result.setResult(Boolean.FALSE);
                        result.setMessage("库存不足");
                    }
                }
            }
        } else {
            result.setResult(Boolean.FALSE);
            result.setMessage("商品不存在");
        }
        return Result.ok(result);
    }

    /**
     * 根据SKUID列表查询库存是否足够
     *
     * @param checkList
     * @return
     */
    @Override
    public Result<PmsSkuCheckStockResult> checkStockBySkuIdList(List<CheckSkuStockParam> checkList) {
        if (CollUtil.isEmpty(checkList)) {
            // 改为返回特定的结果对象，告知调用方参数错误
            PmsSkuCheckStockResult errorResult = new PmsSkuCheckStockResult();
            errorResult.setResult(Boolean.FALSE);
            errorResult.setMessage(SKU_PARAM_NOT_EMPTY.getMsg());
            return Result.ok(errorResult);
        }
        PmsSkuCheckStockResult result = new PmsSkuCheckStockResult();
        result.setResult(Boolean.TRUE);
        StringBuilder message = new StringBuilder();
        List<SkuCheckStockItemResult> skuStockItemList = new ArrayList<>(checkList.size());
        List<Long> itemListIds = checkList.stream().map(CheckSkuStockParam::getSkuId).collect(Collectors.toList());
        List<PmsProductSkuVo> productSkuVoList = skuService.queryByIdList(itemListIds);
        if (CollUtil.isEmpty(productSkuVoList)) {
            result.setResult(Boolean.FALSE);
            result.setMessage("商品不存在");
            result.setSkuStockItemList(skuStockItemList);
            return Result.ok(result);
        }
        Map<Long, PmsProductSkuVo> skuIdAndStockMap = new HashMap<>();
        List<Long> spuIdList = new ArrayList<>();
        for (PmsProductSkuVo productSkuVo : productSkuVoList) {
            skuIdAndStockMap.put(productSkuVo.getId(), productSkuVo);
            if (productSkuVo.getSpuId() != null && !spuIdList.contains(productSkuVo.getSpuId())) {
                spuIdList.add(productSkuVo.getSpuId());
            }
        }
        List<PmsProductSpuVo> spuVoList = spuService.queryByIdList(spuIdList);
        Map<Long, PmsProductSpuVo> spuVoMap = spuVoList.stream().collect(Collectors.toMap(PmsProductSpuVo::getId, Function.identity()));
        for (CheckSkuStockParam item : checkList) {
            SkuCheckStockItemResult itemResult = new SkuCheckStockItemResult();
            itemResult.setMerId(item.getMerId());
            itemResult.setSkuId(item.getSkuId());
            itemResult.setNum(item.getNum());
            itemResult.setResult(Boolean.TRUE);
            PmsProductSkuVo productSkuVo = skuIdAndStockMap.get(item.getSkuId());
            if (productSkuVo == null) {
                itemResult.setResult(Boolean.FALSE);
                itemResult.setMessage("商品不存在");
                appendMessage(message, "商品不存在");
            } else {
                PmsProductSpuVo spuVo = spuVoMap.get(productSkuVo.getSpuId());
                if (spuVo == null) {
                    itemResult.setResult(Boolean.FALSE);
                    itemResult.setMessage("商品不存在");
                    appendMessage(message, "商品不存在");
                } else {
                    if (!Objects.equals(spuVo.getStatus(), ProductSpuStatusEnum.ENABLE.getStatus())) {
                        itemResult.setResult(Boolean.FALSE);
                        itemResult.setMessage("商品已下架");
                        appendMessage(message, "商品已下架");
                    } else {
                        itemResult.setStock(productSkuVo.getStock());
                        if (productSkuVo.getStock() < item.getNum()) {
                            itemResult.setResult(Boolean.FALSE);
                            itemResult.setMessage("库存不足");
                            appendMessage(message, "库存不足");
                        }
                    }
                }
            }
            skuStockItemList.add(itemResult);
        }
        result.setMessage(message.toString());
        result.setSkuStockItemList(skuStockItemList);
        return Result.ok(result);
    }

    /**
     * 实现消息拼接方法
     *
     * @param message
     * @param errorMessage
     * @return
     */
    private StringBuilder appendMessage(StringBuilder message, String errorMessage) {
        if (!message.toString().contains(errorMessage)) {
            message.append(errorMessage + ";");
        }
        return message;
    }

    /**
     * SKUID加库存接口。需要批量和单个,
     *
     * @param updateStockParam
     * @return
     */
    @DSTransactional(rollbackFor = Exception.class)
    @Override
    public Result<SkuUpdateStockResult> addSkuStock(ProductSkuUpdateStockParam updateStockParam) {
        ValidationUtils.validate(updateStockParam);
        SkuUpdateStockResult result = new SkuUpdateStockResult();
        result.setResult(Boolean.TRUE);
        try {
            // 更新 SKU 库存
            List<Long> itemListIds = new ArrayList<>(updateStockParam.getItems().size());
            for (ProductSkuUpdateStockParam.Item item : updateStockParam.getItems()) {
                if (item.getCount() > 0) {
                    itemListIds.add(item.getId());
                    baseMapper.addStockIncr(item.getId(), item.getCount());
                }
            }
            // 更新 SPU 库存
//            Map<Long, Integer> spuIdAndStockMap = spuIdAndStockMap(itemListIds, updateStockParam.getItems());
//            for (Map.Entry<Long, Integer> entry : spuIdAndStockMap.entrySet()) {
//                if (entry.getValue() > 0) {
//                    spuMapper.addStockIncr(entry.getKey(), entry.getValue());
//                }
//            }
        } catch (Exception e) {
            log.error("库存更新失败", e);
            result.setResult(Boolean.FALSE);
            result.setMessage(e.getMessage());
        }
        if (updateStockParam.getIsRollback() && !result.getResult()) {
            throw new ServiceException(result.getMessage());
        }
        if (result.getResult()) {
            result.setMessage("库存更新成功");
        }
        return Result.ok(result);
    }

    /**
     * SKUID减库存接口。需要批量和单个,
     *
     * @param updateStockParam
     * @return
     */
    @DSTransactional(rollbackFor = Exception.class)
    @Override
    public Result<SkuUpdateStockResult> cutSkuStock(ProductSkuUpdateStockParam updateStockParam) {
        ValidationUtils.validate(updateStockParam);
        SkuUpdateStockResult result = new SkuUpdateStockResult();
        result.setResult(Boolean.TRUE);
        try {
            // 更新 SKU 库存
            List<Long> itemListIds = new ArrayList<>(updateStockParam.getItems().size());
            for (ProductSkuUpdateStockParam.Item item : updateStockParam.getItems()) {
                itemListIds.add(item.getId());
                int updateStockIncr = baseMapper.cutStockDecr(item.getId(), item.getCount());
                if (updateStockIncr == 0) {
                    result.setResult(Boolean.FALSE);
                    result.setMessage(result.getMessage() + " " + StrUtil.format("skuId={}商品扣除库存失败", item.getId()));
                }
            }
            // 更新 SPU 库存
//            Map<Long, Integer> spuIdAndStockMap = spuIdAndStockMap(itemListIds, updateStockParam.getItems());
//            for (Map.Entry<Long, Integer> entry : spuIdAndStockMap.entrySet()) {
//                int updateStockIncr = spuMapper.cutStockDecr(entry.getKey(), entry.getValue());
//                if (updateStockIncr == 0) {
//                    result.setResult(Boolean.FALSE);
//                    result.setMessage(result.getMessage() + " " + StrUtil.format("spuId={}商品更新库存失败", entry.getKey()));
//                }
//            }
        } catch (Exception e) {
            log.error("库存更新失败", e);
            result.setResult(Boolean.FALSE);
            result.setMessage(e.getMessage());
        }
        if (updateStockParam.getIsRollback() && !result.getResult()) {
            throw new ServiceException(result.getMessage());
        }
        if (result.getResult()) {
            result.setMessage("库存更新成功");
        }
        return Result.ok(result);
    }

    /**
     * SKUID预加库存 接口。需要批量和单个
     *
     * @param updateStockParam
     * @return
     */
    @Override
    public Result<SkuUpdateStockResult> rollbackPreSkuStock(ProductSkuUpdateStockParam updateStockParam) {
        ValidationUtils.validate(updateStockParam);
        SkuUpdateStockResult result = new SkuUpdateStockResult();
        result.setResult(Boolean.TRUE);
        try {
            // 更新 SKU 库存
            List<Long> itemListIds = new ArrayList<>(updateStockParam.getItems().size());
            for (ProductSkuUpdateStockParam.Item item : updateStockParam.getItems()) {
                itemListIds.add(item.getId());
                int updateStockIncr = baseMapper.addStockForeIncr(item.getId(), item.getCount());
                if (updateStockIncr == 0) {
                    result.setResult(Boolean.FALSE);
                    result.setMessage(result.getMessage() + " " + StrUtil.format("skuId={}预加库存失败", item.getId()));
                }
            }
            // 更新 SPU 库存
//            Map<Long, Integer> spuIdAndStockMap = spuIdAndStockMap(itemListIds, updateStockParam.getItems());
//            for (Map.Entry<Long, Integer> entry : spuIdAndStockMap.entrySet()) {
//                int updateStockIncr = spuMapper.addStockForeIncr(entry.getKey(), entry.getValue());
//                if (updateStockIncr == 0) {
//                    result.setResult(Boolean.FALSE);
//                    result.setMessage(result.getMessage() + " " + StrUtil.format("spuId={}预加库存失败", entry.getKey()));
//                }
//            }
        } catch (Exception e) {
            log.error("预加库存失败", e);
            result.setResult(Boolean.FALSE);
            result.setMessage(e.getMessage());
        }
        if (updateStockParam.getIsRollback() && !result.getResult()) {
            throw new ServiceException(result.getMessage());
        }
        if (result.getResult()) {
            result.setMessage("预加库存成功");
        }
        return Result.ok(result);
    }

    /**
     * SKUID预扣库存接口 接口。需要批量和单个
     *
     * @param updateStockParam
     * @return
     */
    @Override
    public Result<SkuUpdateStockResult> preCutSkuStock(ProductSkuUpdateStockParam updateStockParam) {
        ValidationUtils.validate(updateStockParam);
        SkuUpdateStockResult result = new SkuUpdateStockResult();
        result.setResult(Boolean.TRUE);
        try {
            // 更新 SKU 库存
            List<Long> itemListIds = new ArrayList<>(updateStockParam.getItems().size());
            for (ProductSkuUpdateStockParam.Item item : updateStockParam.getItems()) {
                itemListIds.add(item.getId());
                int updateStockIncr = baseMapper.cutStockForeDecr(item.getId(), item.getCount());
                if (updateStockIncr == 0) {
                    result.setResult(Boolean.FALSE);
                    result.setMessage(result.getMessage() + " " + StrUtil.format("skuId={}预减库存失败", item.getId()));
                }
            }
            // 更新 SPU 库存
//            Map<Long, Integer> spuIdAndStockMap = spuIdAndStockMap(itemListIds, updateStockParam.getItems());
//            for (Map.Entry<Long, Integer> entry : spuIdAndStockMap.entrySet()) {
//                int updateStockIncr = spuMapper.cutStockForeDecr(entry.getKey(), entry.getValue());
//                if (updateStockIncr == 0) {
//                    result.setResult(Boolean.FALSE);
//                    result.setMessage(result.getMessage() + " " + StrUtil.format("spuId={}预减库存失败", entry.getKey()));
//                }
//            }
        } catch (Exception e) {
            log.error("预减库存失败", e);
            result.setResult(Boolean.FALSE);
            result.setMessage(e.getMessage());
        }
        if (updateStockParam.getIsRollback() && !result.getResult()) {
            throw new ServiceException(result.getMessage());
        }
        if (result.getResult()) {
            result.setMessage("预减库存成功");
        }
        return Result.ok(result);
    }

    /**
     * 预扣库存确认扣除
     */
    @Override
    public Result<SkuUpdateStockResult> actCutSkuStock(ProductSkuUpdateStockParam updateStockParam) {
        ValidationUtils.validate(updateStockParam);
        SkuUpdateStockResult result = new SkuUpdateStockResult();
        result.setResult(Boolean.TRUE);
        try {
            // 更新 SKU 库存
            List<Long> itemListIds = new ArrayList<>(updateStockParam.getItems().size());
            for (ProductSkuUpdateStockParam.Item item : updateStockParam.getItems()) {
                itemListIds.add(item.getId());
                int updateStockIncr = baseMapper.actCutStockFore(item.getId(), item.getCount());
                if (updateStockIncr == 0) {
                    result.setResult(Boolean.FALSE);
                    result.setMessage(result.getMessage() + " " + StrUtil.format("skuId={}预扣库存确认扣除失败", item.getId()));
                }
            }
            // 更新 SPU 库存
//            Map<Long, Integer> spuIdAndStockMap = spuIdAndStockMap(itemListIds, updateStockParam.getItems());
//            for (Map.Entry<Long, Integer> entry : spuIdAndStockMap.entrySet()) {
//                int updateStockIncr = spuMapper.actCutStockFore(entry.getKey(), entry.getValue());
//                if (updateStockIncr == 0) {
//                    result.setResult(Boolean.FALSE);
//                    result.setMessage(result.getMessage() + " " + StrUtil.format("spuId={}预扣库存确认扣除失败", entry.getKey()));
//                }
//            }
        } catch (Exception e) {
            log.error("预扣库存确认扣除失败", e);
            result.setResult(Boolean.FALSE);
            result.setMessage(e.getMessage());
        }
        if (updateStockParam.getIsRollback() && !result.getResult()) {
            throw new ServiceException(result.getMessage());
        }
        if (result.getResult()) {
            result.setMessage("预扣库存确认扣除成功");
        }
        return Result.ok(result);
    }

    private Map<Long, Integer> spuIdAndStockMap(List<Long> itemListIds, List<ProductSkuUpdateStockParam.Item> itemList) {
        Assert.notNull(itemListIds);
        List<PmsProductSku> skus = baseMapper.selectBatchIds(itemListIds);
        Map<Long, Long> skuIdAndSpuIdMap = CollectionUtils.convertMap(skus, PmsProductSku::getId, PmsProductSku::getSpuId);
        Map<Long, Integer> spuIdAndStockMap = new HashMap<>(); // SPU 的库存变化 Map 关系
        itemList.forEach(item -> {
            Long spuId = skuIdAndSpuIdMap.get(item.getId());
            if (spuId == null) {
                return;
            }
            Integer stock = spuIdAndStockMap.getOrDefault(spuId, 0) + item.getCount();
            spuIdAndStockMap.put(spuId, stock);
        });
        return spuIdAndStockMap;
    }
}
